package com.intmall.flink.process;

import com.intmall.flink.operator.ClickSource;
import com.intmall.flink.operator.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;

public class TopNExampleProcessAllWindowFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<Event> stream = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event element, long recordTimestamp) {
                                return element.getTimestamp();
                            }
                        }));

        stream.map(data -> data.getUrl())
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(10), Time.seconds(5)))
                .aggregate(new AggregateFunction<String, HashMap<String, Integer>, ArrayList<Tuple2<String, Integer>>>() {
                    @Override
                    public HashMap<String, Integer> createAccumulator() {
                        return new HashMap<>();
                    }

                    @Override
                    public HashMap<String, Integer> add(String value, HashMap<String, Integer> accumulator) {
                        accumulator.put(value, accumulator.containsKey(value) ? accumulator.get(value) + 1 : 1);
                        return accumulator;
                    }

                    @Override
                    public ArrayList<Tuple2<String, Integer>> getResult(HashMap<String, Integer> accumulator) {
                        ArrayList<Tuple2<String, Integer>> result = new ArrayList<>();
                        for (String url : accumulator.keySet()) {
                            result.add(Tuple2.of(url, accumulator.get(url)));
                        }
                        result.sort(new Comparator<Tuple2<String, Integer>>() {
                            @Override
                            public int compare(Tuple2<String, Integer> o1, Tuple2<String, Integer> o2) {
                                return o2.f1 - o1.f1;
                            }
                        });
                        return result;
                    }

                    @Override
                    public HashMap<String, Integer> merge(HashMap<String, Integer> a, HashMap<String, Integer> b) {
                        return null;
                    }
                }, new ProcessAllWindowFunction<ArrayList<Tuple2<String, Integer>>, String, TimeWindow>() {
                    @Override
                    public void process(ProcessAllWindowFunction<ArrayList<Tuple2<String, Integer>>, String, TimeWindow>.Context context, Iterable<ArrayList<Tuple2<String, Integer>>> elements, Collector<String> out) throws Exception {
                        ArrayList<Tuple2<String, Integer>> list = elements.iterator().next();
                        StringBuilder result = new StringBuilder();
                        result.append("窗口结束时间：" + new Timestamp(context.window().getEnd())).append("\n");
                        for (int i = 0; i < 2; i++) {
                            Tuple2<String, Integer> tuple2 = list.get(i);
                            result.append("No.").append(i + 1).append(" url: ")
                                    .append(tuple2.f0).append(" 访问量：").append(tuple2.f1).append("\n");
                        }

                        out.collect(result.toString());
                    }
                })
                .print();
        env.execute();
    }
}
